import 'dart:async';
import 'package:test/test.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart' as sqflite;
import '../entities/user.dart';
import 'user_dao.dart';

void main() {
  late sqflite.Database database;
  late UserDao userDao;
  late StreamController<String> changeListener;

  setUpAll(() async {
    // 初始化sqflite_ffi用于测试
    sqflite.sqfliteFfiInit();
    sqflite.databaseFactory = sqflite.databaseFactoryFfi;
  });

  setUp(() async {
    // 创建内存数据库用于测试
    database = await sqflite.openDatabase(
      ':memory:',
      version: 1,
      onCreate: (db, version) async {
        await db.execute('''
          CREATE TABLE users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            email TEXT NOT NULL UNIQUE,
            age INTEGER NOT NULL,
            status TEXT NOT NULL DEFAULT 'active',
            created_at TEXT,
            updated_at TEXT
          )
        ''');
      },
    );

    changeListener = StreamController<String>.broadcast();
    userDao = UserDao(database, changeListener);
  });

  tearDown(() async {
    await changeListener.close();
    await database.close();
  });

  group('UserDao 基础操作测试', () {
    test('insert - 插入单个用户', () async {
      final user = User(
        name: 'John Doe',
        email: 'john@example.com',
        age: 25,
        status: 'active',
        createdAt: DateTime.now(),
      );

      final id = await userDao.insert(user);
      expect(id, greaterThan(0));
    });

    test('inserts - 批量插入用户', () async {
      final users = [
        User(
          name: 'Alice Smith',
          email: 'alice@example.com',
          age: 30,
          status: 'active',
          createdAt: DateTime.now(),
        ),
        User(
          name: 'Bob Wilson',
          email: 'bob@example.com',
          age: 28,
          status: 'active',
          createdAt: DateTime.now(),
        ),
      ];

      final ids = await userDao.inserts(users);
      expect(ids.length, equals(2));
      expect(ids.every((id) => id > 0), isTrue);
    });

    test('findById - 根据ID查找用户', () async {
      final user = User(
        name: 'Charlie Brown',
        email: 'charlie@example.com',
        age: 35,
        status: 'active',
        createdAt: DateTime.now(),
      );

      final id = await userDao.insert(user);
      final foundUser = await userDao.findById(id);

      expect(foundUser, isNotNull);
      expect(foundUser!.name, equals('Charlie Brown'));
      expect(foundUser.email, equals('charlie@example.com'));
      expect(foundUser.age, equals(35));
    });

    test('findById - 查找不存在的用户', () async {
      final foundUser = await userDao.findById(999);
      expect(foundUser, isNull);
    });

    test('exists - 检查用户是否存在', () async {
      final user = User(
        name: 'David Lee',
        email: 'david@example.com',
        age: 27,
        status: 'active',
        createdAt: DateTime.now(),
      );

      final id = await userDao.insert(user);
      final exists = await userDao.exists(id);
      final notExists = await userDao.exists(999);

      expect(exists, isTrue);
      expect(notExists, isFalse);
    });

    test('update - 更新用户', () async {
      final user = User(
        name: 'Emma Davis',
        email: 'emma@example.com',
        age: 26,
        status: 'active',
        createdAt: DateTime.now(),
      );

      final id = await userDao.insert(user);
      final updatedUser = user.copyWith(
        id: id,
        age: 27,
        status: 'inactive',
        updatedAt: DateTime.now(),
      );

      await userDao.update(updatedUser);
      final foundUser = await userDao.findById(id);

      expect(foundUser!.age, equals(27));
      expect(foundUser.status, equals('inactive'));
      expect(foundUser.updatedAt, isNotNull);
    });

    test('delete - 删除用户', () async {
      final user = User(
        name: 'Frank Miller',
        email: 'frank@example.com',
        age: 32,
        status: 'active',
        createdAt: DateTime.now(),
      );

      final id = await userDao.insert(user);
      final userWithId = user.copyWith(id: id);

      final deletedRows = await userDao.delete(userWithId);
      expect(deletedRows, equals(1));

      final foundUser = await userDao.findById(id);
      expect(foundUser, isNull);
    });

    test('deleteById - 根据ID删除用户', () async {
      final user = User(
        name: 'Grace Wilson',
        email: 'grace@example.com',
        age: 24,
        status: 'active',
        createdAt: DateTime.now(),
      );

      final id = await userDao.insert(user);
      await userDao.deleteById(id);

      final foundUser = await userDao.findById(id);
      expect(foundUser, isNull);
    });

    test('findAll - 查找所有用户', () async {
      final users = [
        User(
          name: 'Henry Adams',
          email: 'henry@example.com',
          age: 29,
          status: 'active',
          createdAt: DateTime.now(),
        ),
        User(
          name: 'Ivy Chen',
          email: 'ivy@example.com',
          age: 23,
          status: 'active',
          createdAt: DateTime.now(),
        ),
      ];

      await userDao.inserts(users);
      final allUsers = await userDao.findAll();

      expect(allUsers.length, greaterThanOrEqualTo(2));
      expect(allUsers.any((u) => u.name == 'Henry Adams'), isTrue);
      expect(allUsers.any((u) => u.name == 'Ivy Chen'), isTrue);
    });

    test('updates - 批量更新用户', () async {
      final users = [
        User(
          name: 'Jack Taylor',
          email: 'jack@example.com',
          age: 31,
          status: 'active',
          createdAt: DateTime.now(),
        ),
        User(
          name: 'Kate Johnson',
          email: 'kate@example.com',
          age: 28,
          status: 'active',
          createdAt: DateTime.now(),
        ),
      ];

      final ids = await userDao.inserts(users);
      final updatedUsers = [
        users[0].copyWith(id: ids[0], status: 'inactive'),
        users[1].copyWith(id: ids[1], age: 29),
      ];

      await userDao.updates(updatedUsers);

      final foundUser1 = await userDao.findById(ids[0]);
      final foundUser2 = await userDao.findById(ids[1]);

      expect(foundUser1!.status, equals('inactive'));
      expect(foundUser2!.age, equals(29));
    });

    test('deletes - 批量删除用户', () async {
      final users = [
        User(
          name: 'Leo Zhang',
          email: 'leo@example.com',
          age: 26,
          status: 'active',
          createdAt: DateTime.now(),
        ),
        User(
          name: 'Mary White',
          email: 'mary@example.com',
          age: 33,
          status: 'active',
          createdAt: DateTime.now(),
        ),
      ];

      final ids = await userDao.inserts(users);
      final usersWithIds = [
        users[0].copyWith(id: ids[0]),
        users[1].copyWith(id: ids[1]),
      ];

      final deletedRows = await userDao.deletes(usersWithIds);
      expect(deletedRows, equals(2));

      final foundUser1 = await userDao.findById(ids[0]);
      final foundUser2 = await userDao.findById(ids[1]);

      expect(foundUser1, isNull);
      expect(foundUser2, isNull);
    });
  });
}
